package com.wang.system.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.common.result.Result;
import com.wang.common.utils.JwtHelper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wang
 * @Date 2024/9/22 19:32
 * @PackageName:com.wang.common.config
 * @ClassName: JwtAuthenticationInterceptor
 * @Description: TODO
 * @Version 1.0
 */
@Component
@Slf4j
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationInterceptor.class);
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        System.out.println("Received Authorization Header: " + token);


        // 如果没有 Token 或者格式不对，返回统一错误响应
//        if (token == null || !token.startsWith("Bearer ")) {
        if (token == null ) {
            handleError(response, Result.fail("缺少或格式错误的Token"));
            return false;  // 返回 false 以阻止后续处理
        }

//        token = token.substring(7);  // 去掉 "Bearer " 前缀

        try {
            // 解析 Token
            Claims claims = jwtHelper.parseToken(token);

            // 判断 Token 是否过期
            if (jwtHelper.isTokenExpired(claims)) {
                handleError(response, Result.fail("Token已过期"));
                return false;
            }
            // 解析成功后设置 tenant_id 到 TenantContext
            String tenantId = claims.get("tenant_id", String.class);
            if (tenantId != null) {
                TenantContext.setTenantId(tenantId);  // 设置租户ID到上下文
                log.info("Set tenantId: " + tenantId);  // 打印日志，便于调试
            } else {
                handleError(response, Result.fail("缺少租户ID"));
                return false;
            }
            // Token 验证成功，继续处理请求
            return true;

        } catch (ExpiredJwtException e) {
            handleError(response, Result.fail("Token已过期"));
            return false;
        } catch (Exception e) {
            handleError(response, Result.fail("Token验证失败"));
            return false;
        }
    }

    // 处理错误响应，将 Result.fail 转为 JSON 并返回
    private void handleError(HttpServletResponse response, Result<?> result) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  // 根据 Result 的状态码返回
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(resultToJson(result));  // 将 Result 转为 JSON
    }

    // 使用 Jackson 将 Result 转为 JSON
    private String resultToJson(Result<?> result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }
}
